import 'package:flutter/rendering.dart';

class LxTextUtil {
  // 计算文本的宽度
  static double computeWidth(String text, double fontSize, double height) {
    return RenderParagraph(
      TextSpan(
        text: text,
        style: TextStyle(fontSize: fontSize),
      ),
      textDirection: TextDirection.ltr,
      maxLines: 1,
    ).computeMaxIntrinsicWidth(height);
  }

  // 计算文本的行数
  static int computeLines(String text, double fontSize, double maxWidth) {
    final span = TextSpan(
      text: text,
      style: TextStyle(fontSize: fontSize),
    );
    final tp = TextPainter(
      text: span,
      textDirection: TextDirection.ltr,
      maxLines: 100,
    );
    tp.layout(maxWidth: maxWidth);
    tp.computeLineMetrics();
    TextSelection selection =
        TextSelection(baseOffset: 0, extentOffset: text.length);

    List<TextBox> boxes = tp.getBoxesForSelection(selection);
    return boxes.length;
  }
}
